package lion.dev.text;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;

/**
 * 处理页面路径的，将相对于本页面的路径处理为指定前缀的路径
 *
 * @author helin
 * @email hl_0074@sina.com
 * @date 2016年11月8日
 */
public class PageURLFormater {

	private static final Pattern URL_PATTERN = Pattern.compile("(src|href|action|bimg)\\s*?=\\s*?['\"](.*?)['\"]");
	private static final Pattern INLINE_CSS_PATTERN = Pattern
			.compile("(background-image|background)\\s*:\\s*?url\\('(.*?)'\\)");

	public static String format(String html, String prefix) throws IOException {

		if (!StringUtils.endsWith(prefix, "/")) {
			prefix += "/";
		}

		Matcher matcher = URL_PATTERN.matcher(html);
		StringBuffer buffer = new StringBuffer();
		while (matcher.find()) {
			matcher.appendReplacement(buffer, matcher.group(1) + "=\"" + getURL(matcher.group(2), prefix) + "\"");
		}
		matcher.appendTail(buffer);

		matcher = INLINE_CSS_PATTERN.matcher(buffer.toString());
		buffer = new StringBuffer();
		while (matcher.find()) {
			matcher.appendReplacement(buffer, matcher.group(1) + ":url('" + getURL(matcher.group(2), prefix) + "')");
		}
		matcher.appendTail(buffer);

		return buffer.toString();
	}

	/**
	 * @param group
	 * @return
	 */
	private static String getURL(String url, String prefix) {

		if (url.matches("^(/|\\w+:|\\.\\.|//:|www.).*")) { return url; }

		return prefix + FilenameUtils.normalize(url, true);
	}
}